<?php
class PanelEditDBRecord extends PageElement
{
	protected $Database;
	protected $Table;
	protected $RecordID = -1;
	protected $OriginalRecordID = 0;
	protected $InnerPanel=false;
	protected $OneToMany=false;
	protected $TypeFieldName;
	protected $TypeTable;
	protected $readOnlyFields = array();
	protected $includeCommentField=false;
	protected $TypeTableID;
	protected $ReadOnly=false;
	protected $DateDisabler=false;
	protected $ParentTable;
	
	private $yearRangeStart=2000; // set the year range for any datetime selects
	private $yearRangeEnd=2020;
	
	public function __Construct($Database,$Table,$RecordID)
	{
//		echo "<br>New PanelEditDBRecord Table=".$Table."    RecordID = ".$RecordID."<br>";
		$this->Database = $Database;
		$this->Table = $Table;
		$this->RecordID = $RecordID;
//		echo "RecordID = ".$RecordID;

		// see if there is a parent table
		$table = new DBTable($Database,$Table);
		$tableStructure = $table->getTableStructure();
//		print_r($tableStructure);
		$keys = array_keys($tableStructure);
		foreach($keys as $key)
		{
			if(substr($key,-3)=="IDP")
			{
				$this->ParentTable=substr($key,0,-3)."s";
//				echo "Parent Table = ".$this->ParentTable."<br>";
				break;
			}
		}
	}

	public function setInnerPanel()
	{
		$this->InnerPanel = true;
	}
	
	public function setReadOnly($readOnly)
	{
		$this->ReadOnly = $readOnly;
	}
	
	public function setDateDisabler($dateDisabler)
	{
//		echo $dateDisabler;
		$this->DateDisabler = $dateDisabler;
//		echo "set as ".$this->DateDisabler."<br>";
	}
	
	public function setOneToMany($onetomany)
	{
		$this->OneToMany = $onetomany;
	}
	
	public function addReadOnlyField($field)
	{
		array_push($this->readOnlyFields,$field);
	}
	
	public function setIncludeCommentField($includeCommentField)
	{
//		echo "Set Include Comment Field ".$includeCommentField."<br>\n";
		$this->includeCommentField = $includeCommentField;
	}
	
	public function setTypeTable($typeFieldName,$typeTable,$typeTableID)
	{
		$this->TypeFieldName = $typeFieldName;
		$this->TypeTable = $typeTable;
		$this->TypeTableID = $typeTableID;
	}
	
	public function setYearRange($aYearStart,$aYearEnd)
	{
		$this->yearRangeStart=$aYearStart;
		$this->yearRangeEnd=$aYearEnd;
	}
	
	
	public function getHTML()
	{
//		echo "now set as ".$this->DateDisabler."<br>";
		$html = "";
		// if typetable specified need to feed this back on save, so create hidden input control
		if(isset($this->TypeTable))
		{
//			echo "typetable=".$this->TypeTable."<br>";
			$hidden = new Hidden();
			$hidden->setName("InsertRecord_".$this->Table."_".substr($this->Table,0,-1)."TypeID");
			$hidden->setValue($this->TypeTableID);
			$html .= $hidden->getHTML();
		}
		$table = new DBTable($this->Database,$this->Table);
		$row=array();
//		echo "table = ".$this->Table." RecordID = ".$this->RecordID."<br>";
		if($this->RecordID != -1)
		{
			$queryField = (isset($this->ParentTable))?substr($this->ParentTable,0,-1)."IDP":$table->getPrimaryKey(); //primary key unless there is a parent table
			$sql = "SELECT * FROM ".$this->Table." WHERE ".$queryField." = ".$this->RecordID;
//			echo $sql."<br>";
			$this->Database->ExecuteSQL($sql);
			$row = $this->Database->getRow();
		}
//		print_r($row);
//		echo "<br>";
		$html .= "<table>\n";
		if($this->InnerPanel)
		{
			$html .= "\n<tr><td colspan=\"2\"><b>".substr($this->Table,0,-1)."</b></td></tr>\n";
		}
		$tableStructure = $table->getTableStructure();
//		print_r($tableStructure);
		$keys = array_keys($tableStructure);
//		$html .= "\n<span>\n";
		foreach($keys as $key)
		{
//			echo $key."<br>";
//			echo $tableStructure[$key];
			if($key == $table->getPrimaryKey())continue;
			if($key =="FSFileName")continue;
			if($key =="FSFileType")continue;
			if($key =="OriginalRecordID")
			{
				if(isset($row[$key]))
					$this->OriginalRecordID = ($row[$key]==0)?$this->RecordID:$row[$key];
				else
					$this->OriginalRecordID = 0;
				$hidden = new Hidden();
				$hidden->setName("InsertRecord_".$this->Table."_OriginalRecordID");
				$hidden->setValue($this->OriginalRecordID);
				$html .= $hidden->getHTML()."\n";
				continue;
			}
//			if($key =="FSFileSize")continue; Use this field to trigger the File input control
			elseif($key==$this->TypeFieldName)
			{
//				echo "this->TypeTable = ".$this->TypeTable."<br>";
//				echo $this->RecordID."<br>";
				$panel = new PanelEditDBRecord($this->Database,$this->TypeTable,$this->RecordID);
				$panel->setYearRange($this->yearRangeStart,$this->yearRangeEnd);			
				if($this->ReadOnly)$panel->setReadOnly(true);
				$panel->setInnerPanel(true);
				$panel->setOneToMany(false);
				$panel->setDateDisabler(true);
				$html .= "\n<tr><td colspan=\"2\">".$panel->getHTML()."</td></tr>\n";
							}
/*			elseif(substr($key,-8)=="IDLN1TO1")
			{
				$panel = new PanelEditDBRecord($this->Database,substr($key,0,-8).'s',-1);
				$panel->setInnerPanel(true);
				$panel->setOneToMany(false);
				$html .= "<tr><td colspan=\"2\">".$panel->getHTML()."</td></tr>";
			}
			elseif(substr($key,-8)=="IDLN1TOM")
			{
				$panel = new PanelEditDBRecord($this->Database,substr($key,0,-8).'s',-1);
				$panel->setInnerPanel(true);
				$panel->setOneToMany(true);
				$html .= "<tr><td colspan=\"2\">".$panel->getHTML()."</td></tr>";
			}*/
			elseif(substr($key,-3)=="IDP") // a link ID to the parent table
			{
			}
			elseif(substr($key,-3)=="IDT") // a link ID from a different table
			{
				//get the record ID in new table
//				echo $this->RecordID."<br>";
				$newTableRecordID=-1;
//				echo "ROW = ";
//				print_r($row);
//				echo "<br>";
				if(isset($row[$key]))$newTableRecordID = $row[$key];
//				echo $this->Table." - ".$newTableRecordID."<br>\n";
	//			echo $this->ParentTable."\n";
				$panel = new PanelSelectIDFromTable($this->Database,substr($key,0,-3).'s',$newTableRecordID,$this->Table,$this->ParentTable);
				if($this->ReadOnly)$panel->setReadOnly(true);
				$html .= "\n<tr><td colspan=\"2\">".$panel->getHTML()."</td></tr>\n";
			}
			elseif(substr($key,-2)=="ID") // an ID from a simple enumeration table 
			{
				$enumeration = new Enumeration($this->Database,substr($key,0,-2).'s');
				$anArray = $enumeration->getArray();
				$arraykeys = array_keys($anArray);
//				foreach($arraykeys as $aKey)
//					echo $aKey.$anArray[$aKey];
//				print_r($anArray);
//				echo "<br>\n";
//				$default = $enumeration->getDefault();
//				echo $row[$key]."<br>";
//				echo $default."<br>";
				$input = new DropDownListEnumeration($anArray);
				$default = $enumeration->getDefault();
				if(isset($row[$key]))
					$input->setSelectedValue($row[$key]);
				elseif(isset($default))
				{
					$input->setSelectedValue($default);
				}
//				$name=($this->InnerPanel)?$this->Table."_".$key:$key;
				$name="InsertRecord_".$this->Table."_".$key;
				$input->setName($name);
				if($this->ReadOnly)$input->setDisabled(true);
				$text="N/A";
				$enum = new Enumeration($this->Database,substr($key,0,-2).'s');
				$arrEnum = $enum->getArray();
				
				if($this->RecordID != -1)
					$text=$arrEnum[$row[$key]];
				$input->setValue($text);
/*				echo "<br>\n";
				print_r($this->readOnlyFields);
				echo "<br>\n";
				print_r($row);
				echo "<br>\n";*/
				if(in_array($key,$this->readOnlyFields))
					$html .= "\n<tr><td>".substr($key,0,-2)."</td><td>".$text."</td></tr>\n";
				else
					$html .= "\n<tr><td>".substr($key,0,-2)."</td><td>".$input->getHTML()."</td></tr>\n";
			}
			elseif($key == "DeletedWhen")
			{
				if(($this->RecordID != -1)&&($row[$key]!=0))
				{
					$datetime = new DateTime($row[$key]);
					$html .= "\n<tr><td style=\"color: #dd0000\">Deleted at</td><td style=\"color: #dd0000\">".$datetime->format("H:i j M Y")."</td></tr>\n";
				}
			}			
			elseif($key == "DeletedBy")
			{
				if(($this->RecordID != -1)&&($row[$key]!=0))
				{
					$users = $this->parentPage->getAuthenticator()->getLongUsers();
					$html .= "\n<tr><td style=\"color: #dd0000\">Deleted by</td><td style=\"color: #dd0000\">".$users[$row[$key]]."</td></tr>\n";
				}
			}
			elseif($key == "CreatedWhen")
			{
				if($this->RecordID != -1)
				{
					$datetime = new DateTime($row[$key]);
					$html .= "\n<tr><td>Created at</td><td>".$datetime->format("H:i j M Y")."</td></tr>\n";
				}
			}
			elseif($key == "CreatedBy")
			{
				if($this->RecordID != -1)
				{
					$users = $this->parentPage->getAuthenticator()->getLongUsers();
					$html .= "\n<tr><td>Created by</td><td>".$users[$row[$key]]."</td></tr>\n";
				}
			}
			elseif($key=="FSFileSize")
			{
//				echo $key." - readonly = ".$this->ReadOnly."<br>";
				if($this->ReadOnly)
				{
					$hidden = new Hidden();
					$hidden->setName("RecordID");
					$html .= $hidden->getHTML();
					
					$hidden = new Hidden();
					$hidden->setName("DBTableName");
					$html .= $hidden->getHTML();
					
					$filename = $row['FSFileName'];
					$filesize = $row['FSFileSize'];
//					echo "Row coming up <br>";
//					print_r($row);
//					echo "<br>";
					$html .= "\n<tr><td>File</td><td><a href=\"javascript:viewFile('".$this->RecordID."','".$this->Table."')\">".$filename." (".$filesize." bytes)</td></tr>\n";
//					<a href=\"javascript:viewFile('".$row['ColumnID']."','".$table->getDBTableName()."')\">View</a>
				} 
				else
				{
					$hidden = new Hidden();
					$hidden->setName("InsertRecord_".$this->Table."_MAXFILESIZE");
					$hidden->setValue("102400");
					$input = new File();
					if($this->ReadOnly)$input->setDisabled(true);
					$name="InsertRecord_".$this->Table."_".$key;
					$input->setName($name);
					
					$html .= $hidden->getHTML()."\n<tr><td>Choose file</td><td>".$input->getHTML()."</td></tr>\n";
				}
			}
			elseif($tableStructure[$key]=="longtext")
			{
//				echo $this->ReadOnly;
				$input = new TextArea();
				$input->setRows(20);
				$input->setColumns(40);
				if($this->ReadOnly)$input->setDisabled(true);
				
				$name="InsertRecord_".$this->Table."_".$key;
				$input->setName($name);
				
				if($this->RecordID != -1)
					$input->setText($row[$key]);
				$html .= "\n<tr><td>".$key."</td><td>".$input->getHTML()."</td></tr>\n";
			}
			elseif($tableStructure[$key]=="text")
			{
				$input = new Textbox();
				$name="InsertRecord_".$this->Table."_".$key;
				$input->setName($name);
				if($this->ReadOnly)$input->setDisabled(true);
				
				if($this->RecordID != -1)
					$input->setValue($row[$key]);
				$html .= "\n<tr><td>".$key."</td><td>".$input->getHTML()."</td></tr>\n";
			}
			elseif(substr($tableStructure[$key],0,3)=="int")
			{
				$input = new Textbox();
				if($this->ReadOnly)$input->setDisabled(true);
				$name="InsertRecord_".$this->Table."_".$key;
				$input->setName($name);
				if($this->RecordID != -1)
					$input->setValue($row[$key]);
				$html .= "\n<tr><td>".$key."</td><td>".$input->getHTML()."</td></tr>\n";
			}
			elseif($tableStructure[$key]=="datetime")
			{
//				echo $key;
				$input = new DateTimeSelect();
				if($this->ReadOnly)$input->setDisabled(true);
				$input->setYearRangeStart($this->yearRangeStart);
				$input->setYearRangeEnd($this->yearRangeEnd);
				$name="InsertRecord_".$this->Table."_".$key;
				$input->setName($name);
				if($this->RecordID != -1)
					$input->setDateTime($row[$key]);
				elseif(isset($_POST['NewRecordDate']))
					$input->setDateTime($_POST['NewRecordDate']);

				$html .= "\n<tr><td>".$key."</td><td>".$input->getHTML()."</td></tr>\n";
			}
			elseif($tableStructure[$key]=="date")
			{
//				echo $key;
				$input = new DateSelect();
//				echo "Disable = ".$this->DateDisabler."<br>";
				if($this->DateDisabler)
				{
//					echo "hello";
					$input->setDisabler(true);
				}
				if($this->ReadOnly)$input->setDisabled(true);
				$input->setYearRangeStart($this->yearRangeStart);
				$input->setYearRangeEnd($this->yearRangeEnd);
				$name="InsertRecord_".$this->Table."_".$key;
				$input->setName($name);
				if($this->RecordID != -1)
					$input->setDate($row[$key]);
				elseif(isset($_POST['NewRecordDate']))
					$input->setDate($_POST['NewRecordDate']);

				$html .= "\n<tr><td>".$key."</td><td>".$input->getHTML()."</td></tr>\n";
			}
			elseif($tableStructure[$key]=="enum('multienum')")
			{
		/*		$sql = "select ".$key."NameID, LongName from ".$key."Names";
				$anArray = array();
				$database = $this->Database->Recopy();
				$database->ExecuteSQL($sql);
				while($row1 = $database->getRow())
				{
					$anArray[$row1[$key.'NameID']] = $row1['LongName'];
				}
//				print_r($anArray);
		*/		
				$sql = "SELECT ".$key."NameID FROM ".$key."s WHERE ".$table->getPrimaryKey()." = ".$this->RecordID;
//				echo $sql."<br>";
				$database = $this->Database->Recopy();
				$database->ExecuteSQL($sql);
				$result = array();
				while($row1 = $database->getRow())
				{
					$result[] = $row1[$key."NameID"];
				}
				
				$enum = new Enumeration($database,$key.'Names');
				$anArray = $enum->getArray();
				$input = new MultiSelectEnumeration($anArray);
				if($this->ReadOnly)$input->setDisabled(true);
				$name="InsertRecord_".$this->Table."_".$key;
				$input->setName($name);
//				print_r($anArray);
//				echo "<br>";
				$input->setSize(count($anArray));

//				print_r ($result);
				$input->setSelected($result);
				$html .= "\n<tr><td>".$key."</td><td>".$input->getHTML()."</td></tr>\n";
			}
			elseif($tableStructure[$key]=="enum('multilevelmultienum')")
			{
		/*		$sql = "select ".$key."NameID, LongName from ".$key."Names";
				$anArray = array();
				$database = $this->Database->Recopy();
				$database->ExecuteSQL($sql);
				while($row1 = $database->getRow())
				{
					$anArray[$row1[$key.'NameID']] = $row1['LongName'];
				}
//				print_r($anArray);
		*/		
				$sql = "SELECT ".$key."NameID FROM ".$key."s WHERE ".$table->getPrimaryKey()." = ".$this->RecordID;
//				echo $sql."<br>";
				$database = $this->Database->Recopy();
				$database->ExecuteSQL($sql);
				$result = array();
				while($row1 = $database->getRow())
				{
					$result[] = $row1[$key."NameID"];
				}
				
				$enum = new Enumeration($database,$key.'Names');
				$anArray = $enum->getArray();
				
				// need to add intermediates to array
				$newkeys=array_keys($anArray);
				foreach ($newkeys as $newkey)
				{
					for ($i=1;$i<strlen($newkey);$i++)
					{
						$anArray[$newkey] = $anArray[substr($newkey,0,0-$i)]." | ".$anArray[$newkey];
					}
				}
				asort($anArray);
				
				$input = new MultiSelectEnumeration($anArray);
				if($this->ReadOnly)$input->setDisabled(true);
				$name="InsertRecord_".$this->Table."_".$key;
				$input->setName($name);
//				print_r($anArray);
//				echo "<br>";
				$input->setSize(count($anArray));

//				print_r ($result);
				$input->setSelected($result);
				$html .= "\n<tr><td>".$key."</td><td>".$input->getHTML()."</td></tr>\n";
			}
			else {}
		}
//		$html .= "\n</span>\n";

//		echo "Include Comment = ".$this->includeCommentField."<br>\n";
		if($this->includeCommentField)
		{
			$ActionComment = new TextArea();
			$ActionComment->setName('ActionComment');
			$ActionComment->setRows(20);
			$ActionComment->setColumns(40);
			$html .= "\n<tr><td>Comment</td><td>".$ActionComment->getHTML()."</td></tr>\n";
		}
		
		
		
		if(($this->InnerPanel==false)&&($this->ReadOnly==false))
		{
			$html .= "\n<tr><td></td><td><hr></td></tr>\n";

			if($this->RecordID != -1)
			{
				$updateButton = new Button();
				$updateButton->setName("Update");
				$updateButton->setValue("Update");
				$updateButton->setOnClick("updateRecord('".$this->RecordID."','".$this->Table."');");
				$html .= "\n<tr><td></td><td>".$updateButton->getHTML()."</td></tr>\n";
			}
	
			$insertButton = new Button();
			$insertButton->setName("Insert");
			$insertButton->setValue("Insert as new");
			$insertButton->setOnClick("insertRecord('".$this->RecordID."','".$this->Table."');");
			
			$html .= "\n<tr><td></td><td>".$insertButton->getHTML();
	
			if ($this->Table == "Events")
			{
				$ddlWeeks = new DropDownList();
				$ddlWeeks->setName("RepeatWeeks");
				$ddlWeeks->setValue("Repeat Weeks");
				$options = array();
				for ($i = 0; $i <= 20; $i++)
					$options[] = new DropDownListOption($i,$i);
				$ddlWeeks->setOptions($options);
				$html .= "and for ".$ddlWeeks->getHTML()." additional weeks";
			}
			$html .= "</td></tr>\n";
	
			$cancelButton = new Button();
			$cancelButton->setName("Cancel");
			$cancelButton->setValue("Cancel");
			$cancelButton->setOnClick("cancel();");
			$html .= "\n<tr><td></td><td>".$cancelButton->getHTML()."</td></tr>\n";

		}
		$html .= "</table>\n";

		return $html;
	}
}
